<template>
    <div style="width: 1000px;  margin:auto;">
        <el-breadcrumb separator-class="el-icon-arrow-right">
        </el-breadcrumb>
        <el-card>
            <el-alert
                    title="发布商品信息"
                    :closable="false"
                    center
                    show-icon
                    type="info">
            </el-alert>
            <el-form
                    ref="addFormRef"
                    :model="addForm"
                    :rules="addFormRules"
                    label-width="80px"
                    label-position="top">
                <el-tabs
                        :tab-position="'left'">
                    <el-tab-pane label="基本信息:" name="0">
                        <el-form-item label="商品名称:" prop="name">
                            <el-input v-model="addForm.name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品售卖的标题:" prop="productTitle">
                            <el-input v-model="addForm.productTitle"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类:" prop="categoryName" >
                            <el-select v-model="addForm.categoryName" :onchange="getCategoryId(addForm.categoryName)" placeholder="选择商品类型">
                                <el-option
                                        v-for="item in cateList"
                                            :key="item.categoryId"
                                            :label="item.categoryName"
                                            :value="item.categoryName"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="商品描述内容:" prop="content">
                            <el-input v-model="addForm.content"></el-input>
                        </el-form-item>
                        <el-form-item label="商品原价格:" prop="buyPrice">
                            <el-input v-model="addForm.buyPrice" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品想卖价格" prop="sellPrice">
                            <el-input v-model="addForm.sellPrice" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品图片" prop="photo">
                            <el-upload
                                    :class="{disabled:uploadDisabled}"
                                    :before-upload="beforeUpload"
                                    action="/api/goods/upload"
                                    accept=".jpg,.png,.gif,.jpeg"
                                    :on-preview="handlePreview"
                                    :on-remove="handleRemove"
                                    :on-success="handleSuccess"
                                    :data="addForm"
                                    list-type="picture">

                                <el-button  size="small" :class="{disabled:uploadDisabled}" type="primary">选取文件</el-button>
                            </el-upload>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button>
                            <el-button @click="resetForm('addFormRef')">重置</el-button>
                        </el-form-item>

                    </el-tab-pane>

                </el-tabs>
            </el-form>
        </el-card>

        <el-dialog
                title="图片预览"
                :visible.sync="previewVisible"
                width="50%">
            <img :src="addForm.photo" alt="" class="previewImg">
        </el-dialog>
    </div>
</template>

<script>
    import _ from 'lodash'

    export default {
        name:"AddGoods",
        data() {
            return {
                activeIndex: "0", // 当前激活的索引
                cateList: "",// 商品分类列表数据,
                previewVisible: false ,// 控制图片预览对话框是否显示
                // 添加商品的表单数据对象
                addForm: {
                    name: "",
                    buyPrice: 0,
                    sellPrice: 0,
                    goods_cat: [],// 商品所属的分类数据
                    categoryName:"手机",
                    goodsType:0,
                    photo:"",
                    picsList:[],// 图片的数组
                    productTitle:'', // 商品的详情描述
                    content:'',
                    studentId:this.$store.getters.getUser.userId,
                },
                // 添加商品表单的验证规则对象
                addFormRules: {
                    name: [
                        { required: true, message: "请输入商品名称", trigger: "blur" }
                    ],
                    productTitle: [
                        { required: true, message: "请输入商品的标题", trigger: "blur" }
                    ],
                    content: [
                        { required: true, message: "请输入商品的详细介绍内容", trigger: "blur" }
                    ],
                    buyPrice: [
                        { required: true, message: "请输入商品原价格", trigger: "blur" }
                    ],
                    sellPrice: [
                        { required: true, message: "请输入商品售卖价格", trigger: "blur" }
                    ],
                    goods_cat: [
                        { required: true, message: "请选择商品分类", trigger: "blur" }
                    ]
                },
            };
        },
        created() {
            this.getCategory();
        },
        methods: {
            // 获取所有商品分类数据
            getCategory() {
                this.$axios
                    .get("/api/goods-category/findAllCategory")
                    .then(res => {
                        this.cateList = res.data;
                    }).catch(err => {
                    return Promise.reject(err);
                });
            },
            getCategoryId(cateName){
                for(var j=0; j<this.cateList.length; j++){
                    if(this.cateList[j].categoryName  == cateName){
                        this.addForm.goodsType =this.cateList[j].categoryId;
                        return this.cateList[j].categoryId;
                    }
                }
            },
            beforeUpload (file) {
                //判断后缀是否正确
                const isJPG = file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/gif'
                if (!isJPG) {
                    this.$message.error('上传图片只能是 JPG,PNG 格式!');
                }
                //限制上传图片2M以内
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                }
                return isJPG &&isLt2M;
            },

            // 处理图片预览效果
            handlePreview(file) {
                this.addForm.photo = file.response.data.url
                this.previewVisible = true

            },

            // 监听图片上传成功的事件
            handleSuccess(res) {
              // 1.拼接得到一个图片信息对象
                const picInfo = {
                    pic:res.tmp_path
                }
                // 2.将图片信息对象，push到picsList组数中
                this.addForm.picsList.push(picInfo)
                this.addForm.photo=res.tmp_path

            },

            // 处理移除图片的操作
            handleRemove(fire) {
                // 1.获取将要删除的图片的临时路径
                const picPath = fire.response.tmp_path
                // 2.从 picsList 数组中，找到这个图片对应的索引值
                const i = this.addForm.picsList.findIndex(x=>x.pic===picPath)// x 代表数组的每一项
                // 3.调用数组的 splice 方法，把图片信息对象，从 picsList 数组中移除
                this.addForm.picsList.splice(i,1)
            },


            resetForm(formName) {
                this.$refs[formName].resetFields();
                this.addForm.photo = '';
            },
            // 点击按钮，添加商品
           addGoods() {
                this.$refs.addFormRef.validate(valid => {
                 // 预校验
                    if(!valid) {
                        return this.$message.error('请先填写必填项！')
                    }
                     // 执行添加的业务逻辑
                    const form = _.cloneDeep(this.addForm)
                     // 请求服务器接口，添加商品window.location.reload();
                    this.$axios.post(
                        "/api/goods/userInsertGoods",form
                    ).then(res => {
                        if (res.data !== "add_success") {
                            return this.$message.error(res.data);
                        }
                        // 路由导航对象.push函数，跳转到指定的路由页面
                        this.$message.success('发布商品成功！')
                        //清空表单
                        this.resetForm('addFormRef')
                        this.$router.push('/')
                       }).catch(err => {
                            return Promise.reject(err);
                       })
                })
            }
        },
        computed: {
            uploadDisabled:function() {
                return this.addForm.picsList.length >0
            },

        },

    };
</script>

<style lang="less" >/*scoped*/
    .el-checkbox {
        margin: 0 10px 0 0 !important;
    }

    .previewImg{
        width: 100%;
    }

    .btnAdd{
        margin-top: 15px;
    }

    .disabled .el-upload--picture {
            display: none;
    }
</style>